package com.zhuqi.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.ArrayList;

/**
 * @author : ZhuQi
 * @version : 时间:2022/6/21 9:57 版本:
 */
@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    private String port;

    /**
     * @param
     * @return
     */
    @GetMapping("test")
    public String method() {
//        String forObject = restTemplate.getForObject("http://order-service/test/curl", String.class);
        try {
            Entry test = SphU.entry("test");
        } catch (BlockException e) {
            e.printStackTrace();
            return "系统忙";
        }
        System.out.println("端口" + port);
        stringRedisTemplate.opsForValue().set("nacos","nacos");
        return "forObject";
    }

    /**
     * @param
     * @return
     */
    @GetMapping("/curl")
    public String method1() {
        System.out.println("端口" + port);
        String  s =  "端口:" + port + "orderService";
        return s;
    }

    /**
     * 定义限流规则
     */
    @PostConstruct
    public void initFlowRules(){
        // 定义限流规则的集合
        ArrayList<FlowRule> flowRules = new ArrayList<>();
        // 创建一个限流规则
        FlowRule flowRule = new FlowRule();
        // 定义一个限流资源
        flowRule.setResource("test");
        // 定义限流规则类型
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 定义QPS 阈值 每秒通过多少请求
        flowRule.setCount(2);
        flowRules.add(flowRule);
        // 加载规则集合
        FlowRuleManager.loadRules(flowRules);
    }

}
